package gu.sql2java.store;

import java.lang.reflect.InvocationTargetException;
import javax.annotation.Nullable;
import com.google.errorprone.annotations.CanIgnoreReturnValue;

/**
 * 条件检查工具类
 * @author guyadong
 *
 */
public class ConditionChecks {

	private ConditionChecks() {
	}
	/**
	 * 执行表达式,为false时抛出 declareType 异常
	 * @param <X> 抛出异常类型
	 * @param b
	 * @param declareType 异常类型
	 * @param errorMessageTemplate a template for the exception message should the check fail. The
	 *     message is formed by replacing each {@code %s} placeholder in the template with an
	 *     argument. These are matched by position - the first {@code %s} gets {@code
	 *     errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted message in
	 *     square braces. Unmatched placeholders will be left as-is.
	 * @param errorMessageArgs the arguments to be substituted into the message template. Arguments
	 *     are converted to strings using {@link String#valueOf(Object)}.
	 * @throws X
	 */
	public static <X extends Throwable> void checkTrue(
			boolean b, 
			Class<X> declareType, 
			@Nullable String errorMessageTemplate, @Nullable Object... errorMessageArgs) throws X {
		if (!b) {
			try {
				if(declareType == null){
					throw new NullPointerException("declareType is null");
				}
				throw declareType.getConstructor(String.class).newInstance(format(errorMessageTemplate, errorMessageArgs));
			} catch (InstantiationException | IllegalAccessException | IllegalArgumentException
					| InvocationTargetException | NoSuchMethodException | SecurityException e) {
				e.printStackTrace();
			}
		}
	}
	/**
	 * 执行表达式,为false时抛出 declareType 异常
	 *
	 * <p>See {@link #checkTrue(boolean, Class, String, Object...)} for details.
	 * @throws X 
	 */
	public static <X extends Throwable> void checkTrue(
			boolean b, 
			Class<X> declareType, 
			@Nullable String errorMessageTemplate, @Nullable Object p1) throws X {
		if (!b) {
			try {
				if(declareType == null){
					throw new NullPointerException("declareType is null");
				}
				throw declareType.getConstructor(String.class).newInstance(format(errorMessageTemplate, p1));
			} catch (InstantiationException | IllegalAccessException | IllegalArgumentException
					| InvocationTargetException | NoSuchMethodException | SecurityException e) {
				e.printStackTrace();
			}	
		}
	}
	/**
	 * reference为{@code null}时抛出 declareType 异常
	 * @param <T> 对象类型
	 * @param <X> 抛出异常类型
	 * @param reference
	 * @param declareType 异常类型
	 * @param errorMessageTemplate a template for the exception message should the check fail. The
	 *     message is formed by replacing each {@code %s} placeholder in the template with an
	 *     argument. These are matched by position - the first {@code %s} gets {@code
	 *     errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted message in
	 *     square braces. Unmatched placeholders will be left as-is.
	 * @param errorMessageArgs the arguments to be substituted into the message template. Arguments
	 *     are converted to strings using {@link String#valueOf(Object)}.
	 * @return T instance
	 * @throws X
	 */
	@CanIgnoreReturnValue
	public static <T,X extends Throwable> T checkNotNull(
			T reference, 
			Class<X> declareType, 
			@Nullable String errorMessageTemplate, @Nullable Object... errorMessageArgs) throws X {
		if (null==reference) {
			try {
				if(declareType == null){
					throw new NullPointerException("declareType is null");
				}
				throw declareType.getConstructor(String.class).newInstance(format(errorMessageTemplate, errorMessageArgs));
			} catch (InstantiationException | IllegalAccessException | IllegalArgumentException
					| InvocationTargetException | NoSuchMethodException | SecurityException e) {
				e.printStackTrace();
			}
		}
		return reference;
	}
	/**
	 * reference为{@code null}时抛出 declareType 异常
	 *
	 * <p>See {@link #checkNotNull(Object, Class, String, Object...)} for details. 
	 * @return T instance
	 * @throws X 
	 */
	@CanIgnoreReturnValue
	public static <T,X extends Throwable> T checkNotNull(
			T reference,
			Class<X> declareType, 
			@Nullable String errorMessageTemplate, @Nullable Object p1) throws X {
		if (null==reference) {
			try {
				if(declareType == null){
					throw new NullPointerException("declareType is null");
				}
				throw declareType.getConstructor(String.class).newInstance(format(errorMessageTemplate, p1));
			} catch (InstantiationException | IllegalAccessException | IllegalArgumentException
					| InvocationTargetException | NoSuchMethodException | SecurityException e) {
				e.printStackTrace();
			}	
		}
		return reference;
	}
	  /**
	   * Substitutes each {@code %s} in {@code template} with an argument. These are matched by
	   * position: the first {@code %s} gets {@code args[0]}, etc. If there are more arguments than
	   * placeholders, the unmatched arguments will be appended to the end of the formatted message in
	   * square braces.
	   *
	   * @param template a non-null string containing 0 or more {@code %s} placeholders.
	   * @param args the arguments to be substituted into the message template. Arguments are converted
	   *     to strings using {@link String#valueOf(Object)}. Arguments can be null.
	   */
	  // Note that this is somewhat-improperly used from Verify.java as well.
	  static String format(String template, @Nullable Object... args) {
	    template = String.valueOf(template); // null -> "null"

	    // start substituting the arguments into the '%s' placeholders
	    StringBuilder builder = new StringBuilder(template.length() + 16 * args.length);
	    int templateStart = 0;
	    int i = 0;
	    while (i < args.length) {
	      int placeholderStart = template.indexOf("%s", templateStart);
	      if (placeholderStart == -1) {
	        break;
	      }
	      builder.append(template, templateStart, placeholderStart);
	      builder.append(args[i++]);
	      templateStart = placeholderStart + 2;
	    }
	    builder.append(template, templateStart, template.length());

	    // if we run out of placeholders, append the extra args in square braces
	    if (i < args.length) {
	      builder.append(" [");
	      builder.append(args[i++]);
	      while (i < args.length) {
	        builder.append(", ");
	        builder.append(args[i++]);
	      }
	      builder.append(']');
	    }

	    return builder.toString();
	  }
}
